import React from 'react'
import { Table, Button, message } from 'antd'
import moment from 'moment'
import Styles from '../styles/table.css'
import { getPromotionList, deleteData, getCategoryList, getProductList } from '../services/restData'

const currencyMap = ['', '$', '₹']

class PromotionList extends React.Component {
  pageSize;
  constructor (props) {
    super(props)
    this.pageSize = 10;
    this.state = {
      loading: true,
      data: null,
      categories: [],
      products: [],
      searchParams: this.props.searchParams,
      pagination: {
        current: 1,
        pageSize: 10,
        actualPageSize: 10,
        position: 'top',
        showTotal: total => `Total ${total} records`,
        total: 0
      },
      sorter: {
        field: null,
        order: null
      },
      reloadCounter: this.props.reloadCounter
    }
  }

  async componentDidMount () {
    const categories = await getCategoryList()
    this.setState({categories})
    const products = await getProductList()
    this.setState({categories, products})
    this.fetchDataFromServer()
  }
  async fetchDataFromServer () {
    this.setState({loading: true})
    this.setState({searchParams: this.props.searchParams})
    const data = await getPromotionList(this.state.searchParams, this.state.pagination.current, this.pageSize)
    let currentPageSize = 0;
    if (data.data.list.length > 0) {
      let list = data.data.list, date = list[0].date, channel = list[0].channelId, total = 0, newList = [];
      list.push({});
      for (let i = 0; i < list.length; i++) {
        console.log(i);
        if (date !== list[i].date || channel !== list[i].channelId) {
          newList[i -1].total = total.toFixed(2);
          date = list[i].date;
          channel = list[i].channelId;
          total = 0;
        }
        total += list[i].cost;
        list[i].total = null;
        if (list[i].id) {
          newList.push(list[i]);
        }

      }
      currentPageSize = newList.length;
      this.setState({data: newList})
    }
    this.setState({loading: false})
    data.page.total = data.page.totalCount
    data.page.current = data.page.currentPage
    // data.page.pageSize = currentPageSize;
    this.setState({pagination: data.page})
  }
  componentDidUpdate (prevProps, prevState, snapshot) {
    if (this.props.searchParams.startDate !== prevProps.searchParams.startDate
      || this.props.searchParams.endDate !== prevProps.searchParams.endDate
      || this.props.searchParams.app !== prevProps.searchParams.app
      || this.props.searchParams.products !== prevProps.searchParams.products
      || this.props.searchParams.channels !== prevProps.searchParams.channels
    ) {
      this.state.searchParams.startDate = this.props.searchParams.startDate
      this.state.searchParams.endDate = this.props.searchParams.endDate
      this.state.searchParams.products = this.props.searchParams.products
      this.state.searchParams.app = this.props.searchParams.app
      this.state.searchParams.channels = this.props.searchParams.channels
      this.fetchDataFromServer()
    }

    if (this.props.reloadCounter !== prevProps.reloadCounter) {
      this.fetchDataFromServer()
    }

  }
  handleChange = (pagination, filter, sorter) => {
    if (pagination.current !== this.state.pagination.current) {
      this.state.pagination.current = pagination.current
      this.fetchDataFromServer()
    }
    if ((sorter.field !== this.state.sorter.field || sorter.order !== this.state.sorter.order ) && Object.keys(sorter).length > 0) {
      this.setState({sorter: sorter})
      this.state.searchParams.sortField = sorter.column.dataIndex;
      this.state.searchParams.sortType = sorter.order.substring(0, sorter.order.length - 3)
      console.log(this.state.searchParams)
      this.fetchDataFromServer()
    }
  }


   deleteRow = async (data) => {
      if ((await deleteData(data.id))) {
            const finalData = this.state.data.filter(row => row.id !== data.id);
            this.setState({data: finalData})
      } else {
        message.error('Error in deleting record')
      }

   }

   updateRow = async (data) => {
      this.props.updateRow(data)
   }

  render () {
    const columns = [
      {
        title: 'Date',
        dataIndex: 'date',
        sorter: true,
        render: (text) => <span>{moment(text).format('YYYY-MM-DD')}</span>
      },
      {
        title: 'Channel',
        dataIndex: 'channelId',
      },
      {
        title: 'App',
        dataIndex: 'appCode',
        render: (text) => !!text ? <span>{this.state.categories.filter(category => category.appCode === text)[0].appName}</span> : ''
      },
      {
        title: 'Product',
        dataIndex: 'productCode',
      },
      {
        title: 'User',
        dataIndex: 'userName',
      },
      {
        title: 'Date Added',
        dataIndex: 'gmtCreate',
        render: (text) => !!text ? <span>{moment(text).format('YYYY-MM-DD')}</span> : ''
      },
      {
        title: 'Cost',
        sorter: true,
          dataIndex: 'cost',
        render: (text, record) => {
          return <span>{currencyMap[record.costIn] + ' ' + Number.parseFloat(text).toFixed(2)}</span>
        }
      },
      {
        title: 'Total',
        sorter: true,
        dataIndex: 'total',
        render: (text, record) => {
          if (text) {
            return <span>{currencyMap[record.costIn] + ' ' + text}</span>
          } else {
            return '';
          }
        }
      },
      {
        title: 'Actions',
        render: (text, record) => {
          return (
            <div>
              <Button type='danger' onClick={()=>this.deleteRow(record)} className='mr10' icon='delete'></Button>
              <Button type='danger' onClick={() => this.updateRow(record)} icon='edit'></Button>
            </div>
          )
        }
      }
    ]
    return (
      <Table className={Styles.promotionTable} bordered columns={columns} dataSource={this.state.data} loading={this.state.loading} onChange={this.handleChange}  pagination={this.state.pagination} rowKey='id'></Table>
    )
  }
}
export default PromotionList
